import 'dart:async';

import 'package:gold/app/order_event.dart';
import 'package:gold/app/user_provider.dart';
import 'package:gold/base/config.dart';
import 'package:gold/base/list_view_model.dart';
import 'package:gold/http/api_order.dart';
import 'package:gold/http/http.dart';
import 'package:gold/model/order_model.dart';
import 'package:gold/route/routes.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:gold/utils/xfg_extension.dart';
import 'package:gold/widgets/dialog/confirm_dialog.dart';
import 'package:gold/widgets/dialog/order_cancel_dialog.dart';

/// @description: 我的低昂单状态
/// @author tangzhentao
/// @created at 21:34 2024/12/14

class MyOrderListViewmodel extends ListViewModel<OrderModel> {
  /// 订单类型 product=商品订单,gold=黄金投资订单,points=积分商品订单
  String orderType;
  /// 订单状态：-1=已取消,0=待支付,1=待发货,2=待收货（待提货）,3=待评价,4=已完成,5=已授权
  /// null的话传''
  final String? orderStatus;

  /// 订单取消或支付此功能的事件
  StreamSubscription<PayingOrderResult>? _payingResultSubscription;
  /// 订单删除的事件
  StreamSubscription<DeleteOrder>? _deleteSubscription;
  /// 已评价订单的事件
  StreamSubscription<ReviewOrder>? _reviewSubscription;
  /// 确认收货订单的事件
  StreamSubscription<ConfirmOrder>? _confirmSubscription;
  /// 已申请退款订单的事件
  StreamSubscription<ApplyingRefundOrder>? _applyingRefundedSubscription;
  /// 已授权订单的事件
  StreamSubscription<AuthorizationOrder>? _authorizationSubscription;

  MyOrderListViewmodel(super.api, this.orderType, this.orderStatus) {
    isLast = false;
    if (orderStatus == null || orderStatus == OrderStatus.paying || orderStatus == OrderStatus.sending || orderStatus == OrderStatus.cancel) {
      _payingResultSubscription = XfgNav.eventBus.on<PayingOrderResult>().listen((result) {
        if (orderStatus == OrderStatus.sending || orderStatus == OrderStatus.cancel) {
          /// 待发货页面，刷新
          refresh();
        } else {
          final id = result.orderId;
          /// 下标
          int index = -1;
          for (var order in list) {
            if (order.id == id) {
              index = list.indexOf(order);
            }
          }
          if (index >= 0) {
            if (orderStatus == OrderStatus.paying) {
              /// 当前待支付页面，移除订单数据
              list.removeAt(index);
              if (list.isNotEmpty) {
                setSuccessChange();
              } else {
                setEmpty();
              }
            } else {
              list[index].status = OrderStatus.cancel;
              setSuccessChange();
            }
          }
        }
      });
    }
    /// 订单删除
    if (orderStatus == null || orderStatus == OrderStatus.cancel) {
      _deleteSubscription = XfgNav.eventBus.on<DeleteOrder>().listen((result) {
        final id = result.orderId;
        /// 下标
        int index = -1;
        for (var order in list) {
          if (order.id == id) {
            index = list.indexOf(order);
          }
        }
        if (index >= 0) {
          list.removeAt(index);
          if (list.isNotEmpty) {
            setSuccessChange();
          } else {
            setEmpty();
          }
        }
      });
    }
    /// 订单已评价
    if (orderStatus == null || orderStatus == OrderStatus.reviewing || orderStatus == OrderStatus.done) {
      _reviewSubscription = XfgNav.eventBus.on<ReviewOrder>().listen((result) {
        if (orderStatus == OrderStatus.done) {
          refresh();
        } else {
          final id = result.orderId;
          /// 下标
          int index = -1;
          for (var order in list) {
            if (order.id == id) {
              index = list.indexOf(order);
            }
          }
          if (orderStatus == OrderStatus.reviewing) {
            /// 当前页面是待评价
            if (index >= 0) {
              list.removeAt(index);
              if (list.isNotEmpty) {
                setSuccessChange();
              } else {
                setEmpty();
              }
            }
          } else {
            /// 当前页面是全部
            if (index >= 0) {
              list[index].status = OrderStatus.done;
              setSuccessChange();
            } else {
              refresh();
            }
          }
        }
      });
    }
    /// 订单已确认收货
    if (orderStatus == null || orderStatus == OrderStatus.receiving || orderStatus == OrderStatus.reviewing) {
      _confirmSubscription = XfgNav.eventBus.on<ConfirmOrder>().listen((result) {
        if (orderStatus == OrderStatus.reviewing) {
          refresh();
        } else {
          final id = result.orderId;
          /// 下标
          int index = -1;
          for (var order in list) {
            if (order.id == id) {
              index = list.indexOf(order);
            }
          }
          if (orderStatus == OrderStatus.receiving) {
            /// 当前页面是待收货
            if (index >= 0) {
              list.removeAt(index);
              if (list.isNotEmpty) {
                setSuccessChange();
              } else {
                setEmpty();
              }
            }
          } else {
            /// 当前页面是全部
            if (index >= 0) {
              list[index].status = OrderStatus.reviewing;
              setSuccessChange();
            } else {
              refresh();
            }
          }
        }
      });
    }
    /// 已申请退款
    if (orderStatus == null || orderStatus == OrderStatus.sending) {
      _applyingRefundedSubscription = XfgNav.eventBus.on<ApplyingRefundOrder>().listen((result) {
        final id = result.orderId;
        /// 下标
        int index = -1;
        for (var order in list) {
          if (order.id == id) {
            index = list.indexOf(order);
          }
        }
        /// 当前页面是全部
        if (index >= 0) {
          list[index].refundStatus = RefundStatus.applying;
          setSuccessChange();
        }
      });
    }
    /// 订单已授权
    if (orderStatus == null || orderStatus == OrderStatus.receiving || orderStatus == OrderStatus.authorized) {
      _authorizationSubscription = XfgNav.eventBus.on<AuthorizationOrder>().listen((result) {
        if (orderStatus == OrderStatus.authorized) {
          refresh();
        } else {
          final id = result.orderId;
          /// 下标
          int index = -1;
          for (var order in list) {
            if (order.id == id) {
              index = list.indexOf(order);
            }
          }
          if (orderStatus == OrderStatus.receiving) {
            /// 当前页面是待提货
            if (index >= 0) {
              list.removeAt(index);
              if (list.isNotEmpty) {
                setSuccessChange();
              } else {
                setEmpty();
              }
            }
          } else {
            /// 当前页面是全部
            if (index >= 0) {
              list[index].status = OrderStatus.authorized;
              setSuccessChange();
            } else {
              refresh();
            }
          }
        }
      });
    }
  }

  /// 去订单详情页面
  void toDetailPage(int index) {
    if (!_isValidOrder(index)) return;
    final order = list[index];
    XfgNav.pushNamed(Routes.myOrderDetail, arguments: {'orderType': orderType, 'orderId': order.id!});
  }

  /// 取消订单
  Future cancelOrder(int index) async {
    if (!_isValidOrder(index)) return;
    final reason = await showOrderCancelDialog();
    if (reason != null) {
      final order = list[index];
      final result = await Http().request<dynamic>(ApiOrder.cancel, data: {'id': order.id, 'reason': reason}, successText: '已取消订单');
      if (result.success) {
        XfgNav.eventBus.fire(PayingOrderResult(order.id!, false));
        XfgNav.read<UserProvider>().updateProfile();
      }
    }
  }

  /// 去付款
  Future toPay(int index) async {
    if (!_isValidOrder(index)) return;
    final order = list[index];
    XfgNav.pushNamed(Routes.pay, arguments: {'type': ProductType.product, 'id': order.id, 'amount': order.payPrice, 'createAt': order.createdAt, 'fromOrder': true});
  }

  /// 处理退款
  Future handleRefund(int index) async {
    final order = list[index];
    if (order.refundStatus == RefundStatus.unApply) {
      XfgNav.pushNamed(Routes.myOrderApplyRefund, arguments: order);
    } else {
      if (!_isValidOrder(index)) return;
      XfgNav.pushNamed(Routes.myOrderRefundApplying, arguments: {
        'orderId': order.id, 'points': order.pointsPrice?? 0,
        'price': (order.payPrice?? 0.00) + (order.amountNum?? 0.00),
        'productLogo' : order.detail?.product?.coverImage, 'productName': order.detail?.product?.name
      });
    }
  }

  /// 查看物流
  Future checkLogistics(int index) async {
    final order = list[index];
    final expressDetail = order.express?.expressDetail;
    if (expressDetail != null && expressDetail.status != null && expressDetail.status != 1 && order.address != null && order.detail?.product != null) {
      XfgNav.pushNamed(Routes.myOrderLogistics, arguments: {
        'product': order.detail?.product!, 'address': order.address!, 'express': expressDetail});
    } else {
      '物流/商品/地址信息异常'.info();
    }
  }

  /// 授权代取
  Future authorizationToCollect(int index) async {
    if (!_isValidOrder(index)) return;
    final order = list[index];
    final result = await XfgNav.pushNamed(Routes.myOrderAuthorizationCollect, arguments: order);
    if (result == true) {
      XfgNav.eventBus.fire(AuthorizationOrder(order.id!));
    }
  }

  /// 我要提货
  Future pickupGoods(int index) async {
    if (!_isValidPickupCode(index)) return;
    final result = await showConfirmDialog(
        title: '提货码:${list[index].pickupCode?? ''}', content: '切勿将您的提货码随意透露给陌生人，以避免不必要的损失',
        notice: '确认代表您已收到货，请谨慎选择!!!', cancel: '取消');
    if (result == true) {
      if (!_isValidOrder(index)) return;
      final order = list[index];
      final result = await Http().request<dynamic>(ApiOrder.confirm, data: {'id': order.id}, successText: '已收货');
      if (result.success) {
        XfgNav.eventBus.fire(ConfirmOrder(order.id!));
        XfgNav.read<UserProvider>().updateProfile();
      }
    }
  }

  /// 确认收货
  Future confirmReceipt(int index) async {
    if (!_isValidOrder(index)) return;
    final confirmResult = await showConfirmDialog(
        title: '确认收货', content: '请确认自己已收到货',
        cancel: '再考虑下');
    if (confirmResult == true) {
      final order = list[index];
      final result = await Http().request<dynamic>(ApiOrder.confirm, data: {'id': order.id}, successText: '已收货');
      if (result.success) {
        XfgNav.eventBus.fire(ConfirmOrder(order.id!));
        XfgNav.read<UserProvider>().updateProfile();
      }
    }
  }

  /// 申请开票
  Future applyForMakingInvoice(int index) async {
    XfgNav.pushNamed(Routes.myOrderApplyInvoice, arguments: 111);
  }

  /// 去评价
  Future goReview(int index) async {
    if (!_isValidOrder(index)) return;
    if (!_isValidProduct(index)) return;
    final order = list[index];
    final product = order.detail?.product;
    if (product != null) {
      final result = await XfgNav.pushNamed(Routes.myOrderAppraise, arguments: {'id': order.id!, 'productId': order.detail!.productId!,'product': product});
      if (result == true) {
        XfgNav.eventBus.fire(ReviewOrder(order.id!));
      }
    } else {
      '商品信息异常'.info();
    }
  }

  /// 删除订单
  Future deleteOrder(int index) async {
    final result = await showConfirmDialog(title: '确认删除订单', content: '删除之后订单无法恢复，无法处理您的 售后问题，请慎重考虑', cancel: '取消');
    if (result == true) {
      final order = list[index];
      final requestResult = await Http().request<dynamic>(ApiOrder.delete, data: {'id': order.id}, successText: '已删除');
      if (requestResult.success) {
        XfgNav.eventBus.fire(DeleteOrder(order.id!));
      }
    }
  }

  /// 再次购买
  Future buyAgain(int index) async {
    if (!_isValidProduct(index)) return;
    final productId = list[index].detail?.productId!;
    if (orderType == ProductType.product) {
      XfgNav.pushNamed(Routes.goodsDetail, arguments: productId);
    } else if (orderType == ProductType.gold) {
      XfgNav.pushNamed(Routes.goldInvest, arguments: productId);
    } else {
      XfgNav.pushNamed(Routes.integralGoods, arguments: productId);
    }
  }

  @override
  Map<String, dynamic>? onOtherData() => {'type': orderType, 'status': orderStatus?? ''};

  /// 有效订单
  bool _isValidOrder(int index) {
    final id = list[index].id;
    final result = id != null;
    if (!result) {
      '订单信息异常'.error();
    }
    return result;
  }

  /// 有效商品
  bool _isValidProduct(int index) {
    final productId = list[index].detail?.productId;
    final result = productId != null;
    if (!result) {
      '商品信息异常'.error();
    }
    return result;
  }

  /// 有效提货码
  bool _isValidPickupCode(int index) {
    final pickupCode = list[index].pickupCode;
    final result = pickupCode?.isNotEmpty == true;
    if (!result) {
      '提货码异常'.error();
    }
    return result;
  }

  @override
  void dispose() {
    _payingResultSubscription?.cancel();
    _payingResultSubscription = null;
    _deleteSubscription?.cancel();
    _deleteSubscription = null;
    _reviewSubscription?.cancel();
    _reviewSubscription = null;
    _confirmSubscription?.cancel();
    _confirmSubscription = null;
    _applyingRefundedSubscription?.cancel();
    _applyingRefundedSubscription = null;
    _authorizationSubscription?.cancel();
    _authorizationSubscription = null;
    super.dispose();
  }
}
